//
//  ZCWebServiceHelper.m
//  Mooc
//
//  Created by ZhangCheng on 15/11/11.
//  Copyright © 2015年 ZhangCheng. All rights reserved.
//

#import "ZCWebServiceHelper.h"

#import "ZCTool.h"

@interface ZCWebServiceHelper(){
}

@end

@implementation ZCWebServiceHelper
/*
+ (instancetype)sharedWebServiceLoader

{
    
    //利用gcd创建一个单例模式 用来上传图片
    
    static ZCWebServiceHelper *loader = nil;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        loader = [[ZCWebServiceHelper alloc]init];
        
    });
    
    return loader;
}
*/


+(void)requestWithMethod:(RequestMethod)requestMethod andUrlStr:(NSString *)urlStr andParameters:(id)parameters andFinished:(void(^)(id response,NSURLSessionDataTask *dataTask))responseBlock{
    
    //成功调用的block
    void (^success)(NSURLSessionDataTask *dataTask, id responseObject) = ^(NSURLSessionDataTask *dataTask,id responseObject)
    {
        NSLog(@"%@",responseObject);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSDictionary *dic = (NSDictionary *)responseObject;
        if (dic[@"code"] && [dic[@"code"] isKindOfClass:[NSNumber class]] && ([dic[@"code"] integerValue] == 200 || [dic[@"code"] integerValue] == 0)) {
            responseBlock(responseObject, dataTask);
        }else{
            if (dic[@"code"] && [dic[@"code"] isKindOfClass:[NSNumber class]] && [dic[@"code"] integerValue] == 401) {
                [UIApplication sharedApplication].keyWindow.rootViewController = [[UIStoryboard storyboardWithName:@"Account" bundle:nil] instantiateInitialViewController];
            }
            [SVProgressHUD showErrorWithStatus:dic[@"msg"]];
        }
    };
    
    //失败调用的block
    void (^failure)(NSURLSessionDataTask *dataTask,NSError *error) = ^(NSURLSessionDataTask *dataTask,NSError *error)
    {
        NSLog(@"网络错误：%@",[error localizedDescription]);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [SVProgressHUD showErrorWithStatus:CONNECTION_ERROR];
    };
    
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", nil];
    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers];
    if (requestMethod == GET) {
        [manager GET:urlStr parameters:parameters progress:nil success:success failure:failure];
    } else {
        [manager POST:urlStr parameters:parameters progress:nil success:success failure:failure];
    }
}


@end
